package com.pinyougou.shop.service;

import com.pinyougou.pojo.Seller;
import com.pinyougou.service.SellerService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;

/** 自定义用户认证类*/
public class UserDetailsServiceImpl implements UserDetailsService {

    /**注入业务层的接口对象 */
    private SellerService sellerService;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {

               //创建角色列表
               List<GrantedAuthority> grantedAuthorityList =new ArrayList<>();
               //向角色列表添加角色
               grantedAuthorityList.add(new SimpleGrantedAuthority("ROLE_SELLER"));
                 /** 根据登录名来查询商家*/
               Seller seller =sellerService.findOne(userName);
               /** 判断商家是否为空，并且商家已审核*/
               if(seller!=null && seller.getStatus().equals("1")){
                   /** 返回用户信息对象 */
                   //创建一个用户对象，向用户添加用户的账号和密码还有角色列表
                   return  new User(userName,seller.getPassword(),grantedAuthorityList);

               }
                return null;

    }
    public void setSellerService(SellerService sellerService) {
        this.sellerService = sellerService;
    }
}
